from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from webdriver_manager.chrome import ChromeDriverManager
import time
import os


def capture_screenshot(url, screenshot_path="./screenshot.png"):
    """
    打开指定URL并截图的函数

    参数:
        url: 需要打开的网页链接
        screenshot_path: 截图保存路径
    """
    global driver
    try:
        # 配置Chrome选项
        chrome_options = Options()
        #chrome_options.add_argument("--headless")  # 无头模式（可选，如需可视化可移除）
        chrome_options.add_argument("--disable-gpu")
        chrome_options.add_argument("--window-size=1920,1080")  # 设置窗口大小

        # 初始化WebDriver
        service = Service(ChromeDriverManager().install())
        driver = webdriver.Chrome(service=service, options=chrome_options)

        # 打开网页
        print(f"正在打开网页: {url}")
        driver.get(url)

        # 等待页面加载（可根据实际情况调整等待时间）
        time.sleep(5)

        # 截图并保存
        os.makedirs(os.path.dirname(screenshot_path), exist_ok=True)
        driver.save_screenshot(screenshot_path)
        print(f"截图已保存至: {screenshot_path}")

    except Exception as e:
        print(f"操作出错: {str(e)}")
    finally:
        # 关闭浏览器
        if 'driver' in locals():
            driver.quit()
            print("浏览器已关闭")


# 执行截图任务
if __name__ == "__main__":
    target_url = "http://10.59.9.8:7007/boss/login"
    capture_screenshot(target_url)